package org.ehe.business.bom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.bom.domain.BomVersion;
import org.ehe.business.bom.mapper.BomVersionMapper;
import org.ehe.business.bom.service.BomStructureService;
import org.ehe.business.bom.service.BomVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * BOM版本服务实现类
 * @author :zhangnn
 * @className :BomVersionServiceImpl
 * @description: TODO
 * @date 2025-07-30 13:57:57
 */
@Slf4j
@Service
public class BomVersionServiceImpl extends ServiceImpl<BomVersionMapper, BomVersion> implements BomVersionService {
    @Autowired
    private BomStructureService bomStructureService;

    /**
     * 获取BOM的当前版本
     */
    public BomVersion getCurrentVersion(Long bomId) {
        QueryWrapper<BomVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("bom_id", bomId)
            //.eq("status", 2) // 已发布状态
            .isNull("expire_date") // 未失效
            .orderByDesc("create_time")
            .last("LIMIT 1");
        return this.getOne(wrapper);
    }

    /**
     * 获取BOM的草稿版本
     */
    public BomVersion getDraftVersion(Long bomId) {
        QueryWrapper<BomVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("bom_id", bomId)
            .eq("status", 0) // 草稿状态
            .orderByDesc("create_time")
            .last("LIMIT 1");
        return this.getOne(wrapper);
    }

    /**
     * 获取BOM的所有版本历史
     */
    public List<BomVersion> getVersionHistory(Long bomId) {
        QueryWrapper<BomVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("bom_id", bomId)
            .orderByDesc("create_time");
        return this.list(wrapper);
    }

    /**
     * 创建新版本（用于BOM变更）
     */
    @Transactional
    public BomVersion createNewVersion(Long bomId, String changeReason, String changeDescription) {
        log.info("创建新版本: bomId={}, changeReason={}", bomId, changeReason);

        String version;
        // 获取当前版本
        BomVersion currentVersion = getCurrentVersion(bomId);
        if (currentVersion == null) {
            version = "1.0.0";
        } else {
            version = currentVersion.getVersionCode();
        }

        // 生成新版本号
        String newVersionCode = generateNextVersionCode(version);

        // 创建新版本记录
        BomVersion newVersion = new BomVersion();
        newVersion.setBomId(bomId);
        newVersion.setVersionCode(newVersionCode);
        newVersion.setVersionName("版本 " + newVersionCode);
        newVersion.setVersionType(determineVersionType(newVersionCode));
        newVersion.setChangeReason(changeReason);
        newVersion.setChangeDescription(changeDescription);
        newVersion.setParentVersionId(currentVersion == null? 0:currentVersion.getId());
        newVersion.setStatus(0); // 草稿状态
        newVersion.setCreateTime(new Date());

        this.save(newVersion);

        // 复制当前版本的BOM结构到新版本
        if(null != currentVersion){
            bomStructureService.copyBomStructure(currentVersion.getId(), newVersion.getId());
        }

        log.info("新版本创建成功: versionId={}, versionCode={}", newVersion.getId(), newVersionCode);
        return newVersion;
    }

    /**
     * 生成下一个版本号
     * 版本号格式: 主版本.次版本.修订版本 (例: 1.0.0, 1.1.0, 1.0.1)
     */
    private String generateNextVersionCode(String currentVersionCode) {
        String[] parts = currentVersionCode.split("\\.");

        if (parts.length == 2) {
            // 当前是主版本.次版本格式，升级为次版本
            int major = Integer.parseInt(parts[0]);
            int minor = Integer.parseInt(parts[1]);
            return major + "." + (minor + 1) + ".0";
        } else if (parts.length == 3) {
            // 当前是主版本.次版本.修订版本格式，升级修订版本
            int major = Integer.parseInt(parts[0]);
            int minor = Integer.parseInt(parts[1]);
            int patch = Integer.parseInt(parts[2]);
            return major + "." + minor + "." + (patch + 1);
        } else {
            // 默认升级次版本
            return currentVersionCode + ".1";
        }
    }

    /**
     * 确定版本类型
     */
    private Integer determineVersionType(String versionCode) {
        String[] parts = versionCode.split("\\.");

        if (parts.length >= 2) {
            int minor = Integer.parseInt(parts[1]);
            if (minor == 0) {
                return 1; // 主版本
            } else {
                return 2; // 次版本
            }
        }

        if (parts.length >= 3) {
            int patch = Integer.parseInt(parts[2]);
            if (patch > 0) {
                return 3; // 修订版本
            }
        }

        return 2; // 默认为次版本
    }

    /**
     * 发布版本
     */
    @Transactional
    public void publishVersion(Long versionId, Long approverId, String approverName) {
        log.info("发布版本: versionId={}, approverId={}", versionId, approverId);

        BomVersion version = this.getById(versionId);
        if (version == null) {
            throw new RuntimeException("版本不存在");
        }

        if (version.getStatus() != 1) {
            throw new RuntimeException("只有审批中的版本才能发布");
        }

        Date now = new Date();

        // 先失效当前有效版本
        BomVersion currentVersion = getCurrentVersion(version.getBomId());
        if (currentVersion != null && !currentVersion.getId().equals(versionId)) {
            currentVersion.setExpireDate(now);
            this.updateById(currentVersion);
        }

        // 发布新版本
        version.setStatus(2); // 已发布
        version.setEffectiveDate(now);
        version.setApproverId(approverId);
        version.setApproverName(approverName);
        version.setApproveTime(now);
        this.updateById(version);

        log.info("版本发布成功: versionId={}", versionId);
    }

    /**
     * 废弃版本
     */
    @Transactional
    public void obsoleteVersion(Long versionId, String obsoleteReason) {
        log.info("废弃版本: versionId={}, reason={}", versionId, obsoleteReason);

        BomVersion version = this.getById(versionId);
        if (version == null) {
            throw new RuntimeException("版本不存在");
        }

        Date now = new Date();

        version.setStatus(3); // 已废弃
        version.setExpireDate(now);
        version.setChangeDescription(version.getChangeDescription() + " [废弃原因: " + obsoleteReason + "]");
        this.updateById(version);

        log.info("版本废弃成功: versionId={}", versionId);
    }

    /**
     * 比较两个版本的差异
     */
    public String compareVersions(Long oldVersionId, Long newVersionId) {
        log.info("比较版本差异: oldVersionId={}, newVersionId={}", oldVersionId, newVersionId);

        // 这里可以实现详细的版本差异比较逻辑
        // 比较BOM结构、物料变更等

        StringBuilder diff = new StringBuilder();
        diff.append("版本差异分析:\n");

        // 获取两个版本的BOM结构进行比较
        // 这里简化处理，实际项目中需要详细实现
        diff.append("- 结构变更: 待实现详细对比逻辑\n");
        diff.append("- 物料变更: 待实现详细对比逻辑\n");
        diff.append("- 成本影响: 待实现详细对比逻辑\n");

        return diff.toString();
    }

    /**
     * 检查版本是否可以编辑
     */
    public boolean isVersionEditable(Long versionId) {
        BomVersion version = this.getById(versionId);
        if (version == null) {
            return false;
        }

        // 只有草稿状态的版本可以编辑
        return version.getStatus() == 0;
    }

    /**
     * 获取版本的子版本列表
     */
    public List<BomVersion> getChildVersions(Long parentVersionId) {
        QueryWrapper<BomVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_version_id", parentVersionId)
            .orderByDesc("create_time");
        return this.list(wrapper);
    }

    /**
     * 回滚到指定版本
     */
    @Transactional
    public BomVersion rollbackToVersion(Long bomId, Long targetVersionId, String rollbackReason) {
        log.info("回滚版本: bomId={}, targetVersionId={}, reason={}", bomId, targetVersionId, rollbackReason);

        BomVersion targetVersion = this.getById(targetVersionId);
        if (targetVersion == null || !targetVersion.getBomId().equals(bomId)) {
            throw new RuntimeException("目标版本不存在或不属于当前BOM");
        }

        // 创建新版本作为回滚版本
        String newVersionCode = generateNextVersionCode(getCurrentVersion(bomId).getVersionCode());

        BomVersion rollbackVersion = new BomVersion();
        rollbackVersion.setBomId(bomId);
        rollbackVersion.setVersionCode(newVersionCode);
        rollbackVersion.setVersionName("回滚版本 " + newVersionCode);
        rollbackVersion.setVersionType(3); // 修订版本
        rollbackVersion.setChangeReason(rollbackReason);
        rollbackVersion.setChangeDescription("回滚到版本 " + targetVersion.getVersionCode());
        rollbackVersion.setParentVersionId(targetVersion.getId());
        rollbackVersion.setStatus(0); // 草稿状态
        rollbackVersion.setCreateTime(new Date());

        this.save(rollbackVersion);

        // 复制目标版本的BOM结构
        bomStructureService.copyBomStructure(targetVersionId, rollbackVersion.getId());

        log.info("版本回滚成功: rollbackVersionId={}", rollbackVersion.getId());
        return rollbackVersion;
    }

    /**
     * 获取版本状态名称
     */
    public String getVersionStatusName(String status) {
        switch (status) {
            case "0": return "草稿";
            case "1": return "审批中";
            case "2": return "已发布";
            case "3": return "已废弃";
            default: return "未知状态";
        }
    }

    /**
     * 获取版本类型名称
     */
    public String getVersionTypeName(Integer versionType) {
        switch (versionType) {
            case 1: return "主版本";
            case 2: return "次版本";
            case 3: return "修订版本";
            default: return "未知类型";
        }
    }
}
